<template>
  <div class="container" style="margin-left:20px;margin-top:20px;">
    <el-tabs v-model="tabName" tab-position="top" type="card" @tab-click="onTabSelected">
      <el-tab-pane v-for="(item) in ruleGroups" :key="item.value" :value="item.value" :label="item.name" :name="item.value + ''">
        <el-row :gutter="20">
          <el-col :span="8">
            <div style="padding-left:15px;font-size: 12px;height:28px;line-height:28px;">是否启用：
              <el-switch
                v-model="enableFlag"
                style="font-size:12px;"
                size="mini"
                active-text="启用"
                inactive-text="禁用"
              />
            </div>
          </el-col>
          <el-col :span="4">
            <div style="text-align: left;">
              <el-button type="primary" size="mini" @click="doSave()">保存</el-button>
            </div>
          </el-col>
        </el-row>
        <ruleTree :ref="treeName + item.value" :parent="currentObj" />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
import { Message } from 'element-ui'
import { parseToString } from '@/utils/datefromat'
import { showNameByValue } from '@/utils/selectUtil'
import ruleTree from './rule-tree'
import { uuid } from '@/utils/uuid'
import {
  findAllRuleGroups,
  findAllOperators,
  findAllDataTypeOperatorMappers,
  findAllMatchValueDataTypeMappers,
  findRuleTreeByRuleGroupId,
  findAllDataTypes,
  addOrUpdate } from '@/api/coi/configuration/rule-config/rule'
import {
  getEmptyRule,
  getDefualtRootNode,
  getEmptyNode,
  getEmptyCondition,
  getEmptyVariableField } from './js/rule-tree'

export default {
  components: { ruleTree },
  props: {
    parent: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      dialog: false,
      loading: false,
      currentObj: this,
      treeName: 'ruleTree',
      tabName: '1',
      tableHeight: window.innerHeight * 0.45,
      ruleGroups: [],
      operators: [],
      dataTypes: [],
      dataTypeOperatorMap: {},
      matchValueDataTypeMap: {},
      rule: this.getEmptyRule(),
      treeData: [],
      nodeTypeData: 'DATA',
      nodeTypeAnd: 'AND',
      nodeTypeOr: 'OR',
      baseUrl: window.appConfig.coiBuyerConfigBaseUrl
    }
  },
  computed: {
    showSaveButton: function() {
      return !this.rule.id
    },
    enableFlag: {
      get: function() {
        return this.rule && this.rule.enableFlag && this.rule.enableFlag === 1
      },
      set: function(val) {
        if (this.rule) {
          console.log('enableFlag: set:' + val)
          if (val) {
            this.rule.enableFlag = 1
          } else {
            this.rule.enableFlag = 0
          }
        }
      }
    }
  },
  created() {
    this.$nextTick(() => {
    })
  },
  mounted() {
    this.$nextTick(() => {
      this.init()
      this.onTabSelected(null)
    })
  },
  methods: {
    uuid,
    getEmptyRule,
    getDefualtRootNode,
    getEmptyNode,
    getEmptyCondition,
    getEmptyVariableField,
    showNameByValue,
    parseToString,
    init() {
      var _this = this
      findAllRuleGroups(this.baseUrl).then(res => {
        if (res) {
          _this.ruleGroups = res.result
        }
      })
      findAllOperators(this.baseUrl).then(res => {
        if (res) {
          _this.operators = res.result
        }
      })
      findAllDataTypes(this.baseUrl).then(res => {
        if (res) {
          _this.dataTypes = res.result
        }
      })
      findAllDataTypeOperatorMappers(this.baseUrl).then(res => {
        if (res && res.result) {
          console.log('findAllDataTypeOperatorMappers')
          res.result.forEach(item => {
            if (item.dataType) {
              _this.dataTypeOperatorMap[item.dataType] = item.operators
            }
          })
        }
      })
      findAllMatchValueDataTypeMappers(this.baseUrl).then(res => {
        if (res && res.result) {
          console.log('findAllMatchValueDataTypeMappers')
          res.result.forEach(item => {
            if (item.dataType) {
              _this.matchValueDataTypeMap[item.dataType] = item.dataTypes
            }
          })
        }
      })
    },
    onTabSelected(val) {
      console.log('onTabSelected: tab name: ' + this.tabName)
      var self = this
      findRuleTreeByRuleGroupId(this.baseUrl, this.tabName).then(res => {
        var data = []
        if (res && res.result && res.result.node) {
          console.log('findRuleTreeByRuleGroupId:' + self.tabName)
          self.rule = res.result
          if (!res.result.node.nodeLevel) {
            res.result.node.nodeLevel = 0
          }
          self.setUUID(res.result.node)
          data.push(res.result.node)
          self.treeData = data
        } else {
          self.rule = self.getEmptyRule()
          self.rule.ruleGroupId = this.tabName
          self.rule.node.uuid = self.uuid()
          data.push(self.rule.node)
          self.treeData = data
        }
      })
    },
    setUUID(node) {
      if (node) {
        node.uuid = this.uuid()
        if (node.children && node.children.length && node.children.length > 0) {
          for (var i = 0; i < node.children.length; i++) {
            // node.children[i].parent = node
            if (!node.children[i].nodeLevel) {
              node.children[i].nodeLevel = node.nodeLevel + 1
            }
            this.setUUID(node.children[i])
          }
        }
      }
    },
    // 用于替换节点的parent/dataTypeOperators，避免JSON.stringify循环依赖错误问题/过滤不必要的数据提交到后台
    replacement(key, value) {
      if (key === 'parent') {
        return null
      }
      if (key === 'dataTypeOperators') {
        return null
      }
      if (key === 'variableField') {
        return null
      }
      return value
    },
    // 保存
    doSave() {
      var _this = this
      this.$confirm('确认保存？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        _this.loading = true
        var json = JSON.stringify(this.rule, this.replacement)
        console.log('rule:' + json)
        var copyRule = JSON.parse(json)
        console.log('copyRule:' + copyRule)
        addOrUpdate(this.baseUrl, copyRule).then(res => {
          if (res) {
            Message({
              message: res.result,
              type: 'success',
              duration: 2 * 1000
            })
          }
        }, err => {
          console.log(err)
        })
      })
    }
  }
}
</script>
<style scoped>
.field-divider >>> .el-divider--horizontal {
  margin: 5px 0px;
}
.container >>> .el-tabs__content{
  padding-left: 0px;
}
</style>
